//
//  JDAlipayManager.swift
//  DragonWallet
//
//  Created by volantPig on 2024/12/19.
//

import UIKit
import SwiftyJSON
// 人脸认证
//import AlipayVerifySDK

class JDAlipayManager: NSObject {
    static let `default` = JDAlipayManager()
    var certifyId: String?
        
    static func pay(_ orderStr: String) {
        
//        AlipaySDK.defaultService().payOrder(orderStr, fromScheme: "JDAlipay", fromUniversalLink: "") { result in
//            print("支付结果:\(result)")
//            
//        }
        
        AlipaySDK.defaultService().payOrder(orderStr, fromScheme: "JDAlipay") { result in
            print("支付结果:\(result)")
        }
        
    }
    
    
}

/// 授权
extension JDAlipayManager {
//    auth_V2WithInfo
    
    /// 支付宝授权 公开对应信息
    static func alipayAuthorizationAction(_ authCompleted: @escaping (([String: Any])->()) )  {
        
        JDNetWorkRequest(.getAlipayPayInfoStr) { responseStr in
            
            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
            if commonModel?.code == "0" {
                let responseDic = JSON(commonModel?.data as Any).dictionaryValue
                let infoStr = responseDic["infoStr"]?.stringValue
                printLog("支付宝infoStr:\(infoStr)")
                
                AlipaySDK.defaultService().auth_V2(withInfo: infoStr, fromScheme: "JDAlipay") { responseDic in
                    print("授权返回的信息:\(responseDic)")
                    
//                    ([AnyHashable("resultStatus"): 9000, AnyHashable("memo"): , AnyHashable("result"): success=true&result_code=200&app_id=2021005107601969&auth_code=3d54b84c734f423f95d8fc2cad86FA33&scope=auth_user&alipay_open_id=20880018885218778922708660117333&user_id=2088502457221332&target_id=1745198642854685546192])
                    
                    
//                    ([AnyHashable("result"): success=true&result_code=200&app_id=2021005107601969&auth_code=c9e4662f37b64414ab660b7b65acVC33&scope=auth_base&alipay_open_id=20880018885218778922708660117333&user_id=2088502457221332&target_id=1743839973697192653939, AnyHashable("resultStatus"): 9000, AnyHashable("memo"): ])
                    
                    
                    
                    let orderState = JSON(responseDic as Any)["resultStatus"].intValue
                    let resultStr = JSON(responseDic as Any)["result"].stringValue
                    switch orderState {
                    case 8000:
                        print("支付正在处理中")
                    case 4000:
                        print("授权失败")
                        
                    case 6001:
                        print("取消授权")
                        
                    case 6002:
                        print("网络错误")
                    case 9000:
                        print("授权成功")
                        
                        let resultArray = resultStr.components(separatedBy: "&")
                        var resultDic = [String: Any]()
                        for subStr in resultArray {
                            
                            let subStrArray = subStr.components(separatedBy: "=")
                            if subStrArray.count >= 2 {
                                let firstStr = JSON(subStrArray.first as Any).stringValue
                                let lastStr = JSON(subStrArray.last as Any).stringValue
                                resultDic[firstStr] = lastStr
                            }
                        }
                        
                        print("授权结果:\(resultDic)")
                        
//                        ["alipay_open_id": "20880018885218778922708660117333", "user_id": "2088502457221332", "target_id": "1743841289419776713948", "result_code": "200", "app_id": "2021005107601969", "scope": "auth_base", "success": "true", "auth_code": "b9601cb95b8b4360b36cafc73b29OX33"]
                        authCompleted(resultDic)
                    default:
                        break
                    }
                    
                    
                    
                    
                }
                
                
//                updateCompleted(JSON(commonModel?.data ?? [:]).dictionary)
////                commonModel?.data
            }
            
            
//            {
//              "code": 0,
//              "msg": "ok",
//              "data": {
//                "infoStr": "apiname=com.alipay.account.auth&app_id=2021005107601969&app_name=mc&auth_type=AUTHACCOUNT&biz_type=openservice&method=alipay.open.auth.sdk.code.get&product_id=APP_FAST_LOGIN&scope=kuaijie&sign_type=RSA2&target_id=1742407137394492039813&sign=JhlL463QOb2/A54NPDAoDYdbXwGPYdoJNEsTbqL35O69rvrotQZLCe82ZqaSXfL1i0xn6jmD5ElBlwMHjxOKiDVGRN0qVs06QsxrncgbXr6UYZCxYVJwRSsBwRYqfQY7LzcYI+Qk+Die65bFrl52TVd04QuADGkWayc93eM8Rk83rQGFq9hXbKpQPJh1rl3MW3TYaQvuGxjT+yQJefOU15arAE00FuPvcyZoxuZ8T3lxCVBMfRPD+axBZ8yOsY4uuX6HjMhg0yR2jwUY4cUbYo2V4q9/mR+HoKIzKjbzIB6jQsdSKCOhenXGGMZKF6kyOcpCOWjAkjEMymuYmqeJNw=="
//              }
//            }
            
            
            
        } failure: { error in
            
        } error: { errorCode in
                
        }

        return;
        
////        https://opendocs.alipay.com/open/218/105325?pathHash=193593d7
//        /**
//         *  快登授权2.0
//         *
//         *  @param infoStr          授权请求信息字串
//         *  @param schemeStr        调用授权的app注册在info.plist中的scheme
//         *  @param completionBlock  授权结果回调，需要调用方在appDelegate中调用processAuth_V2Result:standbyCallback:方法获取授权结果
//         *                          若在授权过程中，调用方应用被系统终止则此block无效(此时会调用'processAuth_V2Result:standbyCallback:'传入的standbyCallback)
//         */
//        AlipaySDK.defaultService().auth_V2(withInfo: "这是一个服务器端返回的接口", fromScheme: "JDAlipay") { responseDic in
//            
//        }
    }
}


///// 人脸认证
//extension JDAlipayManager {
//    /// 认证SDK初始化
//    func verificationInit() {
//        MPVerifySDKService.initSDKService()
//    }
//    
//    func requestCertifyID() {
//        // 请求自己的后台，获取certifyId
//    }
//    
//    func faceVerificationAction(_ currentVC: UIViewController,_ extraParams: [String: Any] = [:]) {
//            
//        /***
//         * 启动服务
//         * @param certifyId 流水ID
//         * @param currentCtr 人脸页面载体 controller, currentCtr 必须基于navigation controller
//         * @param params 扩展参数
//         * @param callback 结果回调
//         */
//        MPVerifySDKService.sharedInstance().verify(with: self.certifyId ?? "", currentCtr: currentVC, extParams: extraParams) { response in
//            //结果code                response?.code
//            //rason                  response?.reason
//            //restCodeSub            response?.retCodeSub
//            //restMessageSub         response?.retMessageSub
//            response?.code;
////            extParams
////            扩展参数，自定义 UI 等操作。
////            NSMutableDictionary *extParams = [NSMutableDictionarynew];
////            设置刷脸圈的颜色，颜色值为六位十六进制字符串：
////            [extParams setValue:@"FF0000"forKey:ZIM_EXT_PARAMS_KEY_FACE_CIRCLE_COLOR];
////            设置网络等待转菊花颜色，颜色值为六位十六进制字符串：
////            [extParams setValue:@"00FF00"forKey:ZIM_EXT_PARAMS_KEY_ACTIVITYINDICATOR_COLOR];
////            设置自定义 UI 资源 bundle 名称（英文），需要调整弹框文案时可进行自定义设置。bundle 内容可查看 APBToygerFacade.bundle 中资源格式进行多语言文案构建，如 zh-Hans.strings 代表中文文案，en.strings 代表英文文案，内容格式为 "customTitle:xxxA"="xxxB"。customTitle 更换为实际自定义 UI 资源 bundle 名称，xxxA 为目标修改文案，xxxB 为修改后的文案，此处文案修改后需要完整测试回归 UI 以及文案变化影响，以免影响用户体验。
////            [extParams setValue:@"customTitle"forKey:ZIM_EXT_PARAMS_KEY_CUSTOM_TITLE];
//            
//            
//            
//        }
//    }
////    ZIMResponseCode 说明
////    状态码    描述
////    ZIMResponseSuccess（1000）    刷脸完成，实际结果需要通过服务端查询结果接口进行结果查询。
////    ZIMInternalError（1001）    刷脸异常。
////    ZIMInterrupt（1003）    验证中断，如用户主动退出、验证超时等。
////    ZIMNetworkfail（2002）    网络失败。
////    ZIMTIMEError（2003）    设备设置时间异常。
////    ZIMResponseFail（2006）    刷脸失败，实际结果需要通过服务端查询结果接口进行结果查询。
//    
//}

